<template>
  <div class="setting-main">
    <!-- 列表 -->
    <el-dialog v-model="dialogTable.visible" ref="dialogTableRef" :title="dialogTable.title" :v-bind="dialogTable" @close="handleClose" >
      <el-tabs v-model="activeName" class="table-tabs">
        <el-tab-pane label="基本配置" name="0">
            <div class="desc">请联系我们的客服协助开通使用！</div>
            <el-form ref="settingFormDataRef" :rules="rules" :model="settingFormData" label-position="right" label-width="auto">
                <el-form-item label="APP Key :" prop="AppKey">
                <el-input v-model="settingFormData.AppKey" clearable placeholder="请输入APP Key" />
                </el-form-item>
                <el-form-item label="APP Secret :" prop="AppSecret">
                <el-input v-model="settingFormData.AppSecret" clearable placeholder="请输入APP Secret" />
                </el-form-item>
            </el-form>
        </el-tab-pane>
        <el-tab-pane label="小程序" name="1">
            <div class="search-title">
                <div class="search-title-left">
                <el-form>
                    <el-form-item class="search-input" label="关键词" prop="keyword">
                    <el-input v-model="searchForm.keyword" clearable placeholder="请输入小程序名称|AppID搜索" />
                    </el-form-item>
                </el-form>
                <el-button class="search-title-btn" type="primary" @click="handlerSearch()">搜索</el-button>
                </div>
                <div class="search-title-right">
                <el-button @click="handlerAdd()">添加</el-button>
                </div>
            </div>
            <el-scrollbar height="340px">
                <el-table
                class="table-list" 
                :data="state.list" 
                style="width: 100%">
                <el-table-column prop="title" label="小程序信息">
                    <template #default="scope">
                    <div class="mini-app-info">
                        <el-image class="mini-app-info-img" :src="scope.row.ThumbURL">
                        <template #error>
                            <IconPicture />
                        </template>
                        </el-image>
                        <div class="mini-app-info-name">{{ scope.row.Title }}</div>
                    </div>
                    </template>
                </el-table-column>
                <el-table-column prop="AppId" label="AppID"></el-table-column>
                <el-table-column prop="UserName" label="原始ID" />
                <el-table-column prop="options" fixed="right" label="操作">
                    <template #default="scope">
                        <el-button size="small" @click="handlerEdit(scope.row)">修改</el-button>
                        <el-button size="small" @click="handlerDel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
                </el-table>
            </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
      <template v-if="activeName === '0'" #footer>
        <span class="dialog-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">
                确定
            </el-button>
        </span>
        </template>
    </el-dialog>
    <!-- 内容 -->
    <Dialog ref="dialogRef" :state="dialogInfo" @confirm="onSubmit(formDataRef)" @cancel="onCancel" >
      <template #default>
        <div class="setting-box">
          <el-form 
            ref="formDataRef"
            class="form-box" 
            :model="formData" 
            :rules="rules"
            label-width="120px">
            <el-form-item label="小程序AppID" prop="AppId">
              <el-input v-model="formData.AppId" clearable placeholder="请输入小程序AppID" />
            </el-form-item>
            <el-form-item label="小程序名称" prop="Title">
              <el-input v-model="formData.Title" clearable placeholder="请输入小程序名称" />
            </el-form-item>
            <el-form-item label="小程序Logo" prop="ThumbURL">
              <el-upload
                class="logo-uploader"
                accept=".jpg,.JPG,.jpeg,.JPEG,.png,.PNG,.gif,.GIF"
                multiple
                :show-file-list="false"
                :http-request="onUploadFile"
                >
                <img v-if="formData.imgUrl" :src="formData.imgUrl" class="logo-img" />
                <div v-else>
                  <el-icon class="logo-icon"><Plus /></el-icon>
                  <div class="logo-icon-desc">点击上传</div>
                </div>
                <template #tip>
                  <div class="logo-tips">
                    图片格式必须为：png,bmp,jpeg,jpg,gif；不可大于2M；建议使用png格式图片，以保持最佳效果；建议图片尺寸为144px*144px
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="原始ID" prop="UserName">
              <el-input v-model="formData.UserName" clearable placeholder="请输入原始ID" /> 
            </el-form-item>
          </el-form>
        </div>
      </template>
    </Dialog>
    <!-- 删除 -->
    <Dialog ref="delRef" :state="delInfo" @confirm="onSubmitDel" @cancel="onCancelDel" >
      <div>确认删除该小程序信息吗？</div>
    </Dialog>
  </div>
</template>
<script setup lang="ts"> 
import { ref, reactive, onMounted, watch } from 'vue'
import Dialog from '@renderer/components/dialog'
import { miniProgramList, miniProgramPut, miniProgramDel } from '@renderer/ajax/api/common'
import { advancedShow, advancedSet } from '@renderer/ajax/api/groupMonitor'
import { store } from '@renderer/store'
import { ElLoading, ElMessage } from 'element-plus'
import { Picture as IconPicture } from '@element-plus/icons-vue'

const emit = defineEmits(['close'])

const dialogTableRef = ref<any>(null)
const formDataRef = ref<any>(null)

const dialogTable = reactive<any>({
  visible: false,
  width: '660px',
  title: '高级设置',
})

const dialogInfo = reactive<any>({
  visible: false,
  width: '580px',
  title: '添加小程序',
  footer: ['取消', '保存', 'right']
})

const delInfo = reactive<any>({
  visible: false,
  width: '500px',
  title: '提示',
  footer: ['取消', '确定', 'right'],
  Id: ''
})

const activeName = ref<any>('0')

const formData = reactive<any>({
  AppId: '',
  ThumbURL: '',
  imgUrl: '',
  UserName: '',
  Title: ''
})

const searchForm = reactive({
  keyword: '',
  page: 1,
  page_size: 15,
  total: 0,
})

const state = reactive<any>({
  list: []
})

const rules = reactive<any>({
  AppKey: [
    { required: true, message: '请输入APP Key', trigger: 'blur' },
  ],
  AppSecret: [
    { required: true, message: '请输入APP Secret', trigger: 'blur' },
  ],
  AppId: [
    { required: true, message: '小程序AppID必填', trigger: 'blur' },
  ],
  Title: [
    { required: true, message: '小程序名称必填', trigger: 'blur' },
  ],
  ThumbURL: [
    { required: true, message: '请上传Logo', trigger: 'blur' },
  ],
  UserName: [
    { required: true, message: '原始ID必填', trigger: 'blur' },
  ],
})

const onCancel = () => {
  dialogInfo.visible = false
}

const onSubmit = async (formRef) => {
  formRef.validate(async (res) => {
    if(res) {
      const params = new FormData()
      if(formData.Id) {
        params.append('Id', formData.Id)
      }
      params.append('appId', formData.AppId)
      params.append('title', formData.Title)
      if(typeof formData.ThumbURL != 'string') {
        params.append('thumbURL', formData.ThumbURL) 
      }
      params.append('userName', formData.UserName)
      let userId = store.getters['common/userId']
      params.append('userId', userId)
      let res = await miniProgramPut(params)
      ElMessage.success('添加成功')
      dialogInfo.visible = false
      getData()
    }
  })
  
}

const onUploadFile = async (row: any) => {
  
  let file = row.file
  console.log(file,'file')
  let ext = file.name.substring(file.name.lastIndexOf('.'))
  const isImg = '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG,.gif,.GIF'.indexOf(ext) == -1
  if (isImg) {
    ElMessage.warning(`该图片是${ext}格式,请上传png,bmp,jpeg,jpg,gif格式图片`)
    return
  }
  if(file.size/1024/1024 > 2) {
    ElMessage.warning(`上传图片超过2M`)
    return
  }
  formData.ThumbURL = file
  const windowURL = window.URL || window.webkitURL;
  const src = windowURL.createObjectURL(file);
  formData.imgUrl = src
}

const onSubmitDel = async () => {
  let params = {
    id: delInfo.Id
  }
  let res = await miniProgramDel(params)
  delInfo.visible = false
  getData()
}

const onCancelDel = () => {
  delInfo.visible = false
}

const handlerAdd = () => {
  formData.Id = ''
  formData.AppId = ''
  formData.imgUrl = ''
  formData.ThumbURL = ''
  formData.UserName = ''
  formData.Title = ''
  dialogInfo.title = '添加小程序'
  dialogInfo.visible = true
}

const handlerEdit = (val?: any) => {
  formData.Id = val.Id
  formData.AppId = val.AppId
  formData.ThumbURL = val.ThumbURL
  formData.imgUrl = val.ThumbURL
  formData.UserName = val.UserName
  formData.Title = val.Title
  dialogInfo.title = '修改小程序'
  dialogInfo.visible = true
  formDataRef.value.validate()
}

const handlerDel = (val?: any) => {
  delInfo.Id = val.Id
  delInfo.visible = true
}

const handlerSearch = () => {
  getData()
}

const getData = async () => {

  let params = {
    keyword: searchForm.keyword,
    Page: searchForm.page || 1,
    PageSize: searchForm.page_size || 15
  }
  let res: any = await miniProgramList(params)
  state.list = res || []
  searchForm.total = res?.Total || 0
}

const handleSizeChange = (val: number) => {
  searchForm.page_size = val
  getData()
}

const handleCurrentChange = (val: number) => {
  searchForm.page = val
  getData()
}

watch(
  () => dialogTable.visible,
  (val) => {
    if (val) {
        getData()
        getSettingData()
    }
  }
)

onMounted(() => {
  // getData()
})

const handleClose = () => {
    emit('close')
}

/* ----------------------------基本配置-start---------------------------- */
const settingFormData = reactive({
    AppKey: '',
    AppSecret: ''
})
const settingFormDataRef = ref()
/**
 * 获取基本配置信息，appkey和appsecret
 */
const getSettingData = async () => {
    let info = store.getters['common/getUserInfo']
    let parasm = {
        CorpId: info.CorpID
    }
    let res: any = await advancedShow(parasm)
    Object.assign(settingFormData, res)
}

const handleCancel = () => {
    dialogTable.visible = false
}

const handleSubmit = async () => {
    const loadingInstance = ElLoading.service({ fullscreen: true })
    try {
        await settingFormDataRef.value.validate()
        const res = await advancedSet({ ...settingFormData })
        console.log('res: ', res);
        ElMessage.success('设置成功')
        dialogTable.visible = false
    } catch (err) {
        if (err.code === 4008) {
            ElMessage.error(err.msg)
        }
    } finally {
        loadingInstance.close()
    }
}
/* ----------------------------基本配置-end---------------------------- */

defineExpose({
  dialogTable
})

</script>
<style lang="scss" scoped>
.el-tabs__nav-wrap::after {
  height: 0px;
}
.setting-main {
  .table-list {
    // padding: 10px 0;
  }
  .search-title {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .search-input {
      margin-bottom: 0px;
    }
    .search-title-left {
      display: flex;
      align-items: center;
      .search-title-btn {
        margin-left: 20px;
      }
    }
  }
  .mini-app-info {
    display: flex;
    align-items: center;
    .mini-app-info-img {
      width: 40px;
      height: 40px;
    }
    .mini-app-info-name {
      padding-left: 4px;
    }
  }
  .setting-box {
    .form-box {
      margin: 16px 0;
      .logo-uploader {
       :deep(.el-upload){
          width: 60px;
          height: 60px;
          border: 1px dashed var(--el-border-color);
          border-radius: 2px;
          position: relative;
        }
        
        .el-icon {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
        }
        .logo-icon-desc {
          position: absolute;
          bottom: 5%;
          left: 50%;
          width: 48px;
          font-size: 12px;
          line-height: 16px;
          transform: translateX(-50%);
        }
        .logo-tips {
          padding-top: 6px;
          line-height: 18px;
          font-size: 12px;
        } 
        .logo-img {

        }
      }
      .form-box-item {

      }
    }
  }
}
.desc {
    padding: 12px 14px;
    line-height: 22px;
    background: rgba(24, 144, 255, 0.07);
    border: 1px solid rgb(64, 149, 229);
    border-radius: 2px;
    margin-bottom: 24px;
}
</style>